<template>
  <el-dialog v-model="dialogVisible" :title="flag === 'add' ? '新增标签' : '修改标签'" width="500px" @close="close" draggable>
    <el-form ref="ruleFormRef" label-width="100px" label-suffix=" :" :rules="rules" :model="fromModel">
      <el-form-item label="标签名字" prop="tag_name">
        <el-input v-model="fromModel.tag_name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { FormInstance } from "element-plus";
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { addTagApi, updateTagApi } from "@/api/modules/article";

const dialogVisible = ref(false);
const flag = ref("");

let fromModel = ref({
  tag_name: "",
  call_back: () => {},
  id: ""
});

const rules = reactive({
  tag_name: [{ required: true, message: "请输入标签名称" }]
});

const openDialog = (v: any, callBack: any, row?: any) => {
  dialogVisible.value = true;
  fromModel.value.call_back = callBack;
  flag.value = v;
  if (v === "edit") {
    (fromModel.value.tag_name = row.tag_name), (fromModel.value.id = row.id);
  } else {
    ruleFormRef?.value?.resetFields();
  }
};
const ruleFormRef = ref<FormInstance>();

const close = () => {
  fromModel.value.id = "";
  fromModel.value.tag_name = "";
  fromModel.value.call_back = () => {};
  dialogVisible.value = false;
};

const cancel = () => {
  close();
};

const submit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (flag.value === "add") {
      await addTagApi({
        tag_name: fromModel.value.tag_name
      });
      ElMessage.success("新增成功！");
      fromModel.value.call_back();
      cancel();
    } else {
      await updateTagApi({
        tag_name: fromModel.value.tag_name,
        id: fromModel.value.id
      });
      ElMessage.success("更新成功！");
      fromModel.value.call_back();
      cancel();
    }
  });
};

defineExpose({ openDialog });
</script>
